package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.storage.*;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.YsCol;
import com.ys.enume.storage.TccLogisticsComprehensiveEnum;
import com.ys.service.storage.TccLogisticsComprehensiveOrderService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 物流订单
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsComprehensiveOrder")
public class ApiInterTccLogisticsComprehensiveOrderController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsComprehensiveOrderController.class);

    @Autowired
    private CommonApiService<TccLogisticsComprehensive> commonApiService;

    @Autowired
    private TccLogisticsComprehensiveOrderService tccLogisticsComprehensiveOrderService;

    @Autowired
    private CheckUtil checkUtil;


    //菜单id
    private Long menuId = MenuId.TCC_LogisticsComprehensive_Order;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccLogisticsComprehensiveOrder:view";
    private final String PERMISSIONS_CHANNEL_DETAIL = "tccLogisticsComprehensiveOrder:channelDetail";//物流渠道详情
    private final String PERMISSIONS_CHANNEL_FEE_DETAIL = "tccLogisticsComprehensiveOrder:channelFeeDetail";//物流渠道费用详情
    private final String PERMISSIONS_INVOICE_EXPORT = "tccLogisticsComprehensiveOrder:invoiceExport";//物流发票导出
    private final String PERMISSIONS_CONFIRM = "tccLogisticsComprehensiveOrder:confirm";//物流确认下单
    private final String PERMISSIONS_LOCATION_IMPORT = "tccLogisticsComprehensiveOrder:locationImport";//物流信息导入
    private final String PERMISSIONS_IMPORT_C88 = "tccLogisticsComprehensiveOrder:importC88";//C88文件批量上传
    private final String PERMISSIONS_CANCEL_ORDER = "tccLogisticsComprehensiveOrder:cancelOrder";//物流订单取消

    private final String PERMISSIONS_API_PLACEORDER = "tccLogisticsComprehensiveOrder:apiPlaceOrder";//api下单
    private final String PERMISSIONS_API_CANCEL = "tccLogisticsComprehensiveOrder:apicancel";//物流订单取消（api）
    private final String PERMISSIONS_API_GETC88 = "tccLogisticsComprehensiveOrder:apiGetC88";//C88文件获取（api）
    private final String PERMISSIONS_API_PRINTTAG = "tccLogisticsComprehensiveOrder:apiPrintTag";//标签获取打印（api）

    private final String PERMISSIONS_API_TRACKING_SEARCH = "tccLogisticsComprehensiveOrder:trackingSearch";//物流轨迹查询

    private final String PERMISSIONS_COUNT_COST = "tccLogisticsComprehensiveOrder:countCost";//按单收费核算
    private final String PERMISSIONS_COUNT_COST_CANCEL = "tccLogisticsComprehensiveOrder:countCostCancel";//按单收费核算取消



    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsComprehensive setSeachSqlWithGrid(TccLogisticsComprehensive cond) throws Exception{

        cond
                .addLeftJoin("TCC_FbaDeliverItem B ON B.id = A.fbaDeliverItemId ")
                .addField("B.fbaBoxUpInfoId")
                .addLeftJoin("TCC_FbaBoxUpInfo E ON E.id = B.FbaBoxUpInfoId")
                .addField("E.boxUpBid")//FBA装箱单号
                .addField("E.fbaNo")//FBA编号
                .addField("E.fbaTrackNo")//FBA追踪编号
                .addField("E.fbaToken")//FbaToken
                .addField("E.fbaId")//FbaId
                .addField("E.fbaWarehouse")//FBA仓库
                .addField("E.fbaWarehouseAddr")//FBA仓库地址
                .addField("E.fbaAmount")//Fba费用
                .addLeftJoin("TCC_FbaBoxUp F ON F.bid = E.BoxUpBid ")
                .addField("F.packToken")//包装组Token
                .addField("F.packId")//包装组Id
                .addField("F.distributionBid")//配货清单号
                .addLeftJoin("TCC_FbaFeeDetails G ON G.sourceBid = B.pbid AND G.sourceType = 1")
                .addField("G.priceTranPredict boxPriceTranPredict")//实际物流费（总）
                .addLeftJoin("TCC_FbaPlan J ON J.bid= A.FbaPlanBid ")
                .addField("J.bid fbaplanBid")//FBA计划单号
                .addField("J.shopId shopId")//店铺信息
                .addField("J.creationMethod")//下单方式
                .addField("J.declarationState")//是否报关
                .addField("J.deliverState")//发货计划
                .addField("J.vgsbm")//运营公司编码
                .addField("J.vgsJc")//运营公司简称
                .addField("J.shopName")//网店名称
                .addField("J.remark")//FBA计划单备注
                .addField("J.evenlyBoxNum")//均分箱数
                .addLeftJoin("TCC_FbaLogisticsMethod K ON K.sourceBid = B.pbid AND K.sourceType = 1")
                .addField("K.logsticsWay")//物流服务名称
                .addLeftJoin("TCC_FbaFeeDetails L ON L.sourceBid = J.bid AND L.sourceType = 0")
                .addField("L.priceTranPredict")//预估物流费（总）
                .addLeftJoin("TS_UserChange U ON U.Id = J.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUser")//制单人

                .addLeftJoin("TS_UserChange U2 ON U2.UserId = A.ConfirmOrderUser ")
                .addField("U2.UserId + '/' + U2.UserName AS _ys_confirmOrderUser")//物流确认下单操作人

                .addLeftJoin("TCC_LogisticsSadFile M ON M.LogisticsComprehensiveId = A.Id ")
                .addField("M.AnnexFile AS annexFile")//C88文件
                .addField("M.id sourceId")

                .addLeftJoin("TCC_LogisticsChannelDetail N ON N.LogInvoiceNo = A.LogInvoiceNo")//物流渠道详情
                .addField("N.Id AS tccLogisticsChannelDetailId")//物流渠道详情Id
                .addLeftJoin("TCC_LogisticsDetailChannelFee O ON O.LogInvoiceNo = A.LogInvoiceNo")//物流渠道费用详情
                .addField("O.Id AS detailChannelFeeId")//物流渠道费用详情Id detailChannelFeeId

                .setOrderby("E.fbaWarehouse ASC,K.logsticsWay ASC");//排序
        ;

        cond.setStatus(TccLogisticsComprehensiveEnum.Status.GENERATED.value);//默认查询：物流订单已生成

        //排序
        cond.setOrderby("A.LogOrderBid DESC");
        //权限
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }





    //查询子列表信息
    @RequestMapping("/searchByRowClick")
    @ResponseBody
    public LayuiTableVoJA searchByRowClick(@ModelAttribute TccLogisticsComprehensive cond, String rowConditions){
        //TccLogisticsComprehensive tccLogisticsComprehensive = JSON.parseObject(rowConditions, TccLogisticsComprehensive.class);
        JSONObject clickInfo = JSON.parseObject(rowConditions);
        TccFbaDeliverItem tccFbaDeliverItem = new TccFbaDeliverItem().setId(Long.parseLong(clickInfo.get("fbaDeliverItemId").toString())).queryFirst();
        cond.addLeftJoin("TCC_FbaDeliverSon B ON B.Pbid = A.fbaDeliverBid ")
                .addField("B.boxNo")//箱号
                .addLeftJoin("TCC_FbaDeliverItem DD ON DD.id = B.FbaDeliverItemId ")
                .addLeftJoin("TCC_FbaBox D ON D.id = B.FbaBoxId ")
                .addField("(CONVERT(varchar(10), cast(D.BoxLong as float)) + '*' + CONVERT(varchar(10), cast(D.BoxWide as float))  + '*' + CONVERT(varchar(10), cast(D.BoxHigh as float))) dimensionsCase")//箱尺寸
                .addField("D.boxWeight")//箱重量
                .addLeftJoin("TCC_FbaBoxDetail C ON C.BoxId = D.id ")
                .addField("C.num")//箱中数量
                .addField("C.purchaseAmount priceIn")//商品采购价
                .addLeftJoin("TCC_FbaBoxUpItem H ON H.id = C.BoxUpItemId ")
                .addField("H.AverageBoxUpNum averageBoxNum")
                .addField("H.goodsLink goodsLink")
                .addField("H.averageBoxUpNum averageBoxUpNum")
                .addLeftJoin("TCC_FbaPlanItem I ON I.id = H.FbaPlanItemId")
                .addField("I.commodityCode,I.commodityName,I.sku,I.numStock,I.numPlanDeliver,I.isSign,I.signCode,I.annexFile,I.asin,I.fnSku,I.codeGoodsHs,I.nameGoodsCn")
                .addField("I.nameMaterialCn,I.weightPackage,I.vck,I.vkq,I.vhw,I.numApiDeliver")
                .addField("(CONVERT(varchar(19), cast(I.lengthPackage as float)) + '*' + CONVERT(varchar(19), cast(I.widthPackage as float))  + '*' + CONVERT(varchar(19), cast(I.heightPackage as float))) packageSize")
                .setOrderby("A.id DESC");//排序

        cond.where("DD.FbaBoxUpInfoId = " + tccFbaDeliverItem.getFbaBoxUpInfoId());
        return commonApiService.searchLay(cond);
    }

    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccLogisticsComprehensive cond,String conditions
    ){
        try {
            cond = setSeachSqlWithGrid(cond);
            //查询条件
            String _ys_createTime = ConditionUtil.getConditionValue(conditions, "_ys_createTime");//物流计划创建时间
            if (_ys_createTime != null && _ys_createTime.length() > 0) {
                String[] timeDays = _ys_createTime.split(" ~ ");
                cond.where("A.createTime >= '" + timeDays[0] + "' and A.createTime <= '" + timeDays[1] + "'");
            }
            String createNameLinked = ConditionUtil.getConditionValue(conditions, "_ys_confirmOrderUser");//物流确认下单操作人
            if (createNameLinked != null){
                cond.where("U2.UserId LIKE '%" + createNameLinked + "%'" + " OR  U2.UserName LIKE '%" + createNameLinked + "%'");
            }

            LayuiTableVoJA searchList =  commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = searchList.getData();

            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));
            List<Map<String, Object>> resultList = new ArrayList();
            //处理数据
            if(resListNew.size()>0) {
                resultList = setList(resListNew);
            }
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
            searchList.setData(jsonArray);

            //合计
            {
                JSONObject JO = new JSONObject();
                //计算累计
                cond.setMainTable("TCC_LogisticsComprehensive");
                // 发票箱数
                JO.put("logInvoiceBox", cond.setFields("ISNULL(SUM(A.LogInvoiceBox),0)").sumDecimal());
                // 发票计重
                JO.put("logInvoiceWeight", cond.setFields("ISNULL(SUM(A.LogInvoiceWeight),0)").sumDecimal());
                // 发票方数
                JO.put("cubeNum", cond.setFields("ISNULL(SUM(A.CubeNum),0)").sumDecimal());

                searchList.setTotalRow(JO);
            }

            return searchList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    //处理返回的数据，将JSON类型转换成具体返回字段
    public List<Map<String, Object>> setList(List<Map<String, Object>> resDate) {
        List<Map<String, Object>> newList = new ArrayList<>();
        for(Map<String, Object> infoMap:resDate){
            if(infoMap.get("logOrderProfitMargin")!=null && !"".equals(infoMap.get("logOrderProfitMargin"))){
                infoMap.put("logOrderProfitMargin", infoMap.get("logOrderProfitMargin").toString()+"%");
            }
            newList.add(infoMap);
        }
        return newList;
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsComprehensive cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSqlWithGrid(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            listData = setList(listData);
            ExportExcelUtils<TccLogisticsComprehensive> util = new ExportExcelUtils<>(new TccLogisticsComprehensive());
            String toFilePath = util.exportExcel(listData, listField, "物流订单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 物流发票导出 - 按物流发票单导出
     */
    @RequiresPermissions(PERMISSIONS_INVOICE_EXPORT)
    @RequestMapping("/invoiceExport")
    @ResponseBody
    public R invoiceExport(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            //根据发票号去重
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas), e->e.get("logInvoiceNo").toString());

            return tccLogisticsComprehensiveOrderService.invoiceExport(detailList);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 物流确认下单
     */
    @RequiresPermissions(PERMISSIONS_CONFIRM)
    @RequestMapping("/confirm")
    @ResponseBody
    public R confirm(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            //根据发票号去重
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas), e->e.get("logInvoiceNo").toString());
            int doCount = 0;
            StringBuilder resMsg = new StringBuilder();
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //处理
                R res = tccLogisticsComprehensiveOrderService.confirm(info.get("logInvoiceNo").toString());
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append((info.get("logInvoiceNo")!=null?"发票号："+info.get("logInvoiceNo"):"")+"；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            StringBuilder resMsgTotal = new StringBuilder().append("成功确认下单").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsgTotal.toString());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 物流订单取消
     */
    @RequiresPermissions(PERMISSIONS_CANCEL_ORDER)
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public R cancelOrder(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            return tccLogisticsComprehensiveOrderService.doCancel(choooseDatas);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    //FBA编码（物流订单C88文件导入调用）
    @RequestMapping("/searchForFbaNo")
    @ResponseBody
    public LayuiTableVoJA searchForFbaNo(Model model, HttpServletRequest request, HttpServletResponse response,
                                                            @ModelAttribute TccLogisticsComprehensive cond, String conditions){

        cond.clearFieldsSource();
        cond.addLeftJoin("TCC_FbaDeliverItem B ON A.FbaDeliverItemId = B.Id")
                .addLeftJoin("TCC_FbaBoxUpInfo C ON C.Id = B.FbaBoxUpInfoId")
                .addField("C.FbaNo AS fbaNo");

        cond.setStatus(TccLogisticsComprehensiveEnum.Status.GENERATED.value);//默认查询：物流订单已生成
        //排序
        cond.setOrderby("C.FbaNo ASC");


        return commonApiService.searchLay(cond);
    }



    //获取FBA编码列表信息
    @RequestMapping("/searchFbaNoList")
    @ResponseBody
    public JSONObject searchFbaNoList(HttpServletRequest request){
        JSONObject res = new JSONObject();
        try {
            List<TccFbaBoxUpInfo> fbaNoList = new TccFbaBoxUpInfo()
                    .addLeftJoin("TCC_FbaDeliverItem B ON B.FbaBoxUpInfoId = A.Id")
                    .addLeftJoin("TCC_LogisticsComprehensive C ON C.FbaDeliverItemId = B.Id")
                    .where("C.Status = "+TccLogisticsComprehensiveEnum.Status.GENERATED.value)//默认查询：物流订单已生成
                    .queryList();
            res.put("code",R.Code.SUCCESS.value);
            res.put("fbaNoList",fbaNoList);
            return res;
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            res.put("code",R.Code.FAILED.value);
            res.put("msg","出错");
            return res;
        }
    }



    /**
     * 保存批量导入的C88文件
     */
    @RequestMapping("/saveC88FileByBatch")
    @ResponseBody
    public R saveC88FileByBatch(HttpServletRequest request, String dataList){
        try {
            //批量导入
            JSONArray detailJA = JSON.parseArray(dataList);
            tccLogisticsComprehensiveOrderService.saveC88FileByBatch(detailJA);
            return R.ok();
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /*
     * 物流综合（物流付款_关税费调用）
     */
    @RequestMapping("/searchModalByPayGs")
    @ResponseBody
    public LayuiTableVoJA searchModalByPayGs(@ModelAttribute TccLogisticsComprehensive cond, String conditions){
        cond
                //物流订单对账说明 logOrderlDesDz
//                .addLeftJoin("TCC_LogisticsComprehensive SB ON SB.Id = A.LogisticsComprehensiveId")//物流信息表
//                .addField("SB.FbaNo AS fbaNo") //FBA编号
//                .addField("SB.SpOrderBid AS spOrderBid") // 服务商订单号
//                .addField("SB.ServiceTariff AS serviceTariff")//        服务商关税费用（导入）
//                .addField("SB.RateDuty AS rateDuty")//        关税利率
//                .addField("SB.SpTariffAmount AS spTariffAmount")//        服务商关税金额（支付）
//                .addField("SB.LogInvoiceCost AS logInvoiceCost")//        物流发票费用（总）
//                .addField("SB.LogInvoiceSalesFee AS logInvoiceSalesFee")//        物流销售费用（总）
//                .addField("SB.LogChannelName AS logChannelName")//        物流渠道名称
//                .addField("SB.FbaDeliverBid AS fbaDeliverBid")//                FBA发货单号
//                .addField("SB.FbaBoxUpBid AS fbaBoxUpBid")//        FBA装箱单号
//                .addField("SB.FbaPlanBid AS fbaPlanBid")//        FBA计划单号
                .addField("A.Id AS logisticsComprehensiveId")
                .addField("A.ServiceTariff - A.SpTariffAmount AS payAmount")//默认支付金额

                .addLeftJoin("TCC_FbaPlan SC ON SC.Bid = A.FbaPlanBid")//FBA计划
                .addField("SC.DeliverState AS deliverState")//               发货计划（1按SKU自动发货，0按箱自动发货）
                .addField("CASE WHEN SC.DeliverState = 1 THEN '按SKU自动发货'  ELSE '按箱自动发货' END deliverStateTxt")// 发货计划（1按SKU自动发货，0按箱自动发货）


                .addField("SC.Vgsbm AS vgsbm")//        运营公司编码
                .addField("SC.VgsJc AS vgsJc")//                运营公司简称
                .addField("SC.DeclarationState AS declarationState")//                是否报关
                .addField("SC.ShopName AS shopName")//                网店名称

                .addField("CASE WHEN SC.DeclarationState = 1 THEN '是'  ELSE '否' END declarationStateTxt")// 是否报关

                .addLeftJoin("TCC_FbaDeliverItem SD ON SD.Id = A.FbaDeliverItemId")//FBA发货单号详情id（TCC_FbaDeliverItem）
                .addLeftJoin("TCC_FbaBoxUpInfo SE ON SE.Id = SD.FbaBoxUpInfoId")//装箱单FBA信息
                .addField("SE.FbaWarehouse AS fbaWarehouse")//        FBA仓库
                .addField("SE.FbaTrackNo AS fbaTrackNo")//        FBA追踪编号

                .addLeftJoin("TCC_LogisticsChannelDetail SF ON SF.LogInvoiceNo = A.LogInvoiceNo")//物流渠道详情表
                .addField("SF.LogsticsWay AS logsticsWay")// 物流服务名称



        .setTariffZfStatus(TccLogisticsComprehensiveEnum.TariffZfStatus.COMPLETE.value)//已关税
        .where("A.ServiceTariff != A.SpTariffAmount")
        .setIsFirstByInvoice(1)

        ;
        return commonApiService.searchLay(cond);
    }



    /*
     * 物流综合（物流付款_物流费调用）
     */
    @RequestMapping("/searchModalByPayWl")
    @ResponseBody
    public LayuiTableVoJA searchModalByPayWl(@ModelAttribute TccLogisticsComprehensive cond, String conditions){
        cond
                //物流订单对账说明 logOrderlDesDz

                .addField("A.Id AS logisticsComprehensiveId")
                .addField("A.SpLogsticsFee - A.LogSpAmount AS payAmount")//默认支付金额


                .addField("CASE " +
                        "WHEN A.LogOrderStatusDz = 0 THEN '' " +
                        "WHEN A.LogOrderStatusDz = 1 THEN '盈利' " +
                        "WHEN A.LogOrderStatusDz = 2 THEN '低利润' " +
                        "WHEN A.LogOrderStatusDz = 3 THEN '亏损' " +
                        " ELSE '' END logOrderStatusDzTxt")

                .addLeftJoin("TCC_FbaPlan SC ON SC.Bid = A.FbaPlanBid")//FBA计划
                .addField("SC.DeliverState AS deliverState")//               发货计划（1按SKU自动发货，0按箱自动发货）
                .addField("SC.Vgsbm AS vgsbm")//        运营公司编码
                .addField("SC.VgsJc AS vgsJc")//                运营公司简称
                .addField("SC.DeclarationState AS declarationState")//                是否报关
                .addField("SC.ShopName AS shopName")//                网店名称

                .addField("CASE WHEN SC.DeliverState = 1 THEN '按SKU自动发货'  ELSE '按箱自动发货' END deliverStateTxt")// 发货计划（1按SKU自动发货，0按箱自动发货）

                .addField("CASE WHEN SC.DeclarationState = 1 THEN '是'  ELSE '否' END declarationStateTxt")// 是否报关

                .addLeftJoin("TCC_FbaDeliverItem SD ON SD.Id = A.FbaDeliverItemId")//FBA发货单号详情id（TCC_FbaDeliverItem）
                .addLeftJoin("TCC_FbaBoxUpInfo SE ON SE.Id = SD.FbaBoxUpInfoId")//装箱单FBA信息
                .addField("SE.FbaWarehouse AS fbaWarehouse")//        FBA仓库
                .addField("SE.FbaTrackNo AS fbaTrackNo")//        FBA追踪编号

                .addLeftJoin("TCC_LogisticsChannelDetail SF ON SF.LogInvoiceNo = A.LogInvoiceNo")//物流渠道详情表
                .addField("SF.LogsticsWay AS logsticsWay")// 物流服务名称

                .addLeftJoin("TCC_LogisticsServiceProvider SG ON SG.ProviderBid = SF.ProviderCode")//物流服务商表
                .addField("SG.Name AS providerName")// 物流服务商名称

                .where("A.SpLogsticsFee IS NOT NULL  AND A.SpLogsticsFee != A.LogSpAmount")
                .setIsFirstByInvoice(1)

        ;
        return commonApiService.searchLay(cond);
    }




    /**
     * api下单
     */
    @RequiresPermissions(PERMISSIONS_API_PLACEORDER)
    @RequestMapping("/apiPlaceOrder")
    @ResponseBody
    public R apiPlaceOrder(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            //根据发票号去重
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas), e->e.get("logInvoiceNo").toString());
            int doCount = 0;
            StringBuilder resMsg = new StringBuilder();
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //处理
                R res = tccLogisticsComprehensiveOrderService.apiPlaceOrder(info.get("logInvoiceNo").toString());
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append((info.get("logInvoiceNo")!=null?"发票号："+info.get("logInvoiceNo"):""))
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            StringBuilder resMsgTotal = new StringBuilder().append("成功api下单").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsgTotal.toString());
        } catch (IllegalArgumentException e) {
            logger.error("出错："+e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        } catch (Exception e) {
            logger.error("出错："+e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 物流订单取消（api）
     */
    @RequiresPermissions(PERMISSIONS_API_CANCEL)
    @RequestMapping("/apicancel")
    @ResponseBody
    public R apicancel(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            List<Map<String, Object>> choooseList = ToolUtil.jsonArrayToList(JSON.parseArray(choooseDatas));
            return tccLogisticsComprehensiveOrderService.apiCancel(choooseList);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * C88文件获取（api）
     */
    @RequiresPermissions(PERMISSIONS_API_GETC88)
    @RequestMapping("/apiGetC88")
    @ResponseBody
    public R apiGetC88(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            List<Map<String, Object>> choooseList = ToolUtil.jsonArrayToList(JSON.parseArray(choooseDatas));
            return tccLogisticsComprehensiveOrderService.apiGetC88(choooseList);

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 标签获取打印（api）
     */
    @RequiresPermissions(PERMISSIONS_API_PRINTTAG)
    @RequestMapping("/apiPrintTag")
    @ResponseBody
    public R apiPrintTag(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //获取数据
            String choooseDatas = params.get("choooseDatas").toString();
            List<Map<String, Object>> choooseList = ToolUtil.jsonArrayToList(JSON.parseArray(choooseDatas));
            return tccLogisticsComprehensiveOrderService.apiPrintTag(choooseList);

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }





    /**
     * 物流轨迹查询
     */
    @RequiresPermissions(PERMISSIONS_API_TRACKING_SEARCH)
    @RequestMapping("/trackingSearch")
    @ResponseBody
    public R trackingSearch(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("logInvoiceNo")==null){
                return R.error("发票号为空");
            }
            //获取数据
            String logInvoiceNo = params.get("logInvoiceNo").toString();
            return tccLogisticsComprehensiveOrderService.trackingSearch(logInvoiceNo);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 按单收费核算
     */
    @RequiresPermissions(PERMISSIONS_COUNT_COST)
    @RequestMapping("/countCost")
    @ResponseBody
    public R countCost(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("logisticsMarkingBid")==null){
                return R.error("物流订单标记为空");
            }
            //获取数据
            String logisticsMarkingBid = params.get("logisticsMarkingBid").toString();
            return tccLogisticsComprehensiveOrderService.countCost(logisticsMarkingBid);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 按单收费核算取消
     */
    @RequiresPermissions(PERMISSIONS_COUNT_COST_CANCEL)
    @RequestMapping("/countCostCancel")
    @ResponseBody
    public R countCostCancel(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("logisticsMarkingBid")==null){
                return R.error("物流订单标记为空");
            }
            //获取数据
            String logisticsMarkingBid = params.get("logisticsMarkingBid").toString();
            return tccLogisticsComprehensiveOrderService.countCostCancel(logisticsMarkingBid);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }






}
